package LinkedList;//输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
//
// 
//
// 示例 1： 
//
// 输入：head = [1,3,2]
//输出：[2,3,1] 
//
// 
//
// 限制： 
//
// 0 <= 链表长度 <= 10000 
// Related Topics 栈 递归 链表 双指针 👍 200 👎 0


//leetcode submit region begin(Prohibit modification and deletion)

import java.util.ArrayList;
import java.util.Stack;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint1(ListNode head) {
        /**
         * 栈
         * */
        Stack<Integer> stack = new Stack<>();
        while(head!=null){
            stack.push(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        int index = 0;
        while(!stack.isEmpty()){
            res[index++] = stack.pop();
        }
        return res;
    }

    ArrayList<Integer> reset = new ArrayList<>();
    public int[] reversePrint2(ListNode head) {
        /**
         * 递归*/
        reverse(head);
        int[] res = new int[reset.size()];
        for (int i = 0; i < reset.size(); i++) {
            res[i] = reset.get(i);
        }
        return res;

    }
    void reverse(ListNode head){
        if(head == null){
            return;
        }
        reverse(head.next);
        reset.add(head.val);

    }
    public int[] reversePrint(ListNode head) {
        /**两次循环*/
        //先获取链表长度，创建对应长度数组
        ListNode currNode = head;
        int len = 0;
        while(currNode != null){
            len ++;
            currNode = currNode.next;
        }
        int[] result = new int[len];

        //再次遍历链表，将值倒序填充至结果数组
        currNode = head;
        while(currNode != null){
            result[len - 1] = currNode.val;
            len --;
            currNode = currNode.next;
        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
